package com.henghai.zhenxuan.ui.page.login;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.MainActivity;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.bean.HttpBean;
import com.henghai.zhenxuan.data.bean.LoginBean;
import com.henghai.zhenxuan.domain.request.AccountRequester;
import com.henghai.zhenxuan.domain.request.UserInfoRequester;
import com.henghai.zhenxuan.utils.AppSigning;
import com.henghai.zhenxuan.utils.HiRes;
import com.henghai.zhenxuan.utils.Utils;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseActivity;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.architecture.utils.ToastUtils;

public class LoginActivity extends BaseActivity {

    private LoginStates mStates;
    private AccountRequester mAccountRequester;
    private UserInfoRequester mUserInfoRequester;


    private static final String TAG = "LoginActivity";
    public static void launch(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(LoginStates.class);
        mUserInfoRequester = getActivityScopeViewModel(UserInfoRequester.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mUserInfoRequester.getTokenResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(dataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            Log.d(TAG, "onCreate: "+dataResult.getResult().getData());
            AppConfig.INSTANCE.getMConfigs().user().set(dataResult.getResult().getData());
            WaitDialog.dismiss();
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();

        });

        mAccountRequester.getTokenResult().observe(this, dataResult -> {
            Log.d(TAG, "onCreate: "+dataResult.getResponseStatus());
            if (!dataResult.getResponseStatus().isSuccess()) {
                WaitDialog.dismiss();
                TipDialog.show(dataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            HttpBean<LoginBean> loginDataHttpData = dataResult.getResult();
            if (loginDataHttpData.getData() == null || TextUtils.isEmpty(loginDataHttpData.getData().getToken())) {
                return;
            }

            AppConfig.INSTANCE.getMConfigs().token().set(loginDataHttpData.getData().getToken());
            AppConfig.INSTANCE.getMConfigs().userName().set(mStates.name.get());
            AppConfig.INSTANCE.getMConfigs().userPwd().set(mStates.password.get());

            AppConfig.INSTANCE.getMConfigs().login().set(loginDataHttpData.getData());
            Log.d(TAG, "onCreate: "+loginDataHttpData.getData().toString());
            mUserInfoRequester.request(this);

        });
        mStates.sha1.set(AppSigning.getSha1(this));
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(com.henghai.zhenxuan.R.layout.fragment_login, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    public class ClickProxy {
        public void login() {
            if (!mStates.privacyAgree.get()) {
                ToastUtils.showLongToast("请您阅读并同意下方协议");
                return;
            }
            if (TextUtils.isEmpty(mStates.name.get()) || TextUtils.isEmpty(mStates.password.get())) {
                ToastUtils.showLongToast(getString(R.string.username_or_pwd_incomplete));
                return;
            }

            mAccountRequester.requestLogin(LoginActivity.this, mStates.name.get(), mStates.password.get(),getPackageName(), Utils.getSha1(LoginActivity.this));
            WaitDialog.show("正在登录...");
        }

        public void browse() {
            mStates.browse.set(!mStates.browse.get());
            if (mStates.browse.get()) {
                mStates.check.set(R.mipmap.browse_icon_n);
            } else {
                mStates.check.set(R.mipmap.browse_icon_y);
            }
        }
        //注册
        public void register() {
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
        }

        //重置密码
        public void forgotPwd() {
            startActivity(new Intent(LoginActivity.this,ForgotPwdActivity.class));
//            Log.d("------", "forgotPwd: "+checkApplication("com.baitai.integral"));
        }
        /**
         * 卸载应用
         */
        private void uninstallApplication() {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.setAction("android.intent.action.DELETE");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse("package:com.baitai.integral"));
            // startActivity(intent);
            startActivityForResult(intent, 0);
        }

        public boolean checkApplication(String packageName) {
            if (packageName == null || "".equals(packageName)){
                return false;
            }
            try {
                ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
                return true;
            } catch (PackageManager.NameNotFoundException e) {
                return false;
            }
        }

    }


    public static class LoginStates extends StateHolder {
        public final State<Boolean> browse = new State<>(false);

        public final State<String> name = new State<>("");
        public final State<String> sha1 = new State<>("");
        public final State<String> password = new State<>("");
        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<Integer> check = new State<Integer>(R.mipmap.browse_icon_y);

        public final State<Boolean> privacyAgree = new State<>(false);
        public final State<String> privacyContent = new State<>(HiRes.INSTANCE.getString(R.string.privacy_agree));

    }
}
